<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="88px" label-position="left">
          <el-form-item label="会员手机号" prop="phoneNumber">
            <el-input v-model="queryParams.phoneNumber" placeholder="请输入会员手机号" clearable style="width: 200px"
              @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="会员姓名" prop="memberName">
            <el-input v-model="queryParams.memberName" placeholder="请输入会员姓名" clearable style="width: 200px"
              @keyup.enter="handleQuery" />
          </el-form-item>


          <el-form-item label="开始时间">
            <el-date-picker clearable v-model="queryParams.startTime" type="date" value-format="YYYY-MM-DD 00:00:00"
              placeholder="请选择开始时间" style="width: 200px">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="结束时间">
            <el-date-picker clearable v-model="queryParams.stopTime" type="date" value-format="YYYY-MM-DD 23:59:59"
              placeholder="请选择结束时间" style="width: 200px">
            </el-date-picker>
          </el-form-item>



          <el-form-item>
            <el-button type="primary" @click="handleData">当天新增</el-button>
            <el-button type="primary" @click="handleDatatime(2)">三日内新增</el-button>
            <el-button type="primary" @click="handleDatatime(6)">一周内新增</el-button>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>

          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd"
              v-hasPermi="['primary:member:edit']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
              v-hasPermi="['primary:member:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
              v-hasPermi="['primary:member:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport"
              v-hasPermi="['primary:member:export']">导出</el-button>
          </el-col>
          <!--        <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" @click="handledaochu()"
              v-hasPermi="['primary:member:edit']">导出模版</el-button>
          </el-col> -->

<!--          <el-col :span="1.5">
            <el-button type="primary" plain icon="Upload" @click="handleFile">导入模版</el-button>
          </el-col> -->
          <!-- <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar> -->
        </el-row>
      </template>
      <el-table v-loading="loading" :data="memberList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <!-- <el-table-column label="会员卡id" align="center" prop="cardId" /> -->
        <el-table-column label="会员姓名" align="center" prop="memberName" />
        <el-table-column label="会员类型" align="center" prop="memberType">
          <template v-slot="{ row }">
            {{ row.memberType == 0 ? '正式会员' : '准会员' }}
          </template>
        </el-table-column>
        <el-table-column label="会员性别" align="center">
          <template #default="scope">
            <dict-tag :options="sys_user_sex" :value="scope.row.memberSex" />
          </template>
        </el-table-column>
        <el-table-column label="会员手机号" align="center" prop="phoneNumber" />
        <el-table-column label="会员状态" align="center" prop="isValid">
          <template v-slot="{ row }">
            {{ row.isValid == 0 ? '有效会员' : '过期会员' }}
          </template>
        </el-table-column>
        <!-- <el-table-column label="会员身份证" align="center" prop="idCard" /> -->
        <!-- <el-table-column label="会员地址" align="center" prop="memberAddress" /> -->
        <!-- <el-table-column label="对象存储主键" align="center" prop="ossId" /> -->
        <!--        <el-table-column label="会员生日" align="center" prop="birthday" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.birthday, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column> -->
        <!--        <el-table-column label="下发状态" align="center">
          <template #default="scope">
            <dict-tag :options="sys_sync_status" :value="scope.row.syncStatus" />
          </template>
        </el-table-column> -->
        <el-table-column label="跟进人" align="center" prop="coachName" />
        <!--        <el-table-column label="下发详情" show-overflow-tooltip>
          <template #default="{ row }">
            <el-tooltip placement="top" v-if="row.memberSyncList !== null">
              <template #content>
                <div v-for="item in row.memberSyncList">
                  <span style="margin-right: 10px"> 相机名称：{{ item.deviceName }} </span>
                  <span style="margin-right: 10px"> 同步状态：
                    {{ item.syncStatus == 1 ? '已同步' : item.syncStatus == 3 ? '删除中' : '未同步' }}</span>
                  <span v-if="item.failReason !== null"> 失败原因：{{ item.failReason }} </span>
                </div>
                <br />
              </template>
              <el-tag effect="dark" :type="row.memberSyncType == 0 ? 'success' : 'danger'">
                {{ row.memberSyncType == 0 ? '已同步' : row.memberSyncType == 1 ? '未同步' : '删除中' }}
              </el-tag>
            </el-tooltip>
            <el-tag v-if="row.memberSyncList == null" effect="dark"
              :type="row.memberSyncType == 0 ? 'success' : 'danger'">
              {{ row.memberSyncType == 0 ? '已同步' : row.memberSyncType == 1 ? '未同步' : '删除中' }}
            </el-tag>
          </template>
        </el-table-column> -->


        <!--        <el-table-column label="下发详情" align="center">
          <template #default="scope">
            <div v-for="item in scope.row.memberSyncList">
              <span> 相机名称:{{ item.deviceName }}-
                {{item.syncStatus == 0 ? '未同步' : item.syncStatus == 1 ? '已同步' :
              item.syncStatus == 2 ? '同步中' : item.syncStatus == 3 ? '删除中' : '未知状态' }};
              </span>
              <span v-if="item.failReason !== null"> 失败原因:{{ item.failReason }} </span>
            </div>
          </template>
        </el-table-column> -->


        <!-- <el-table-column label="会员卡名称" align="center" prop="cardName" /> -->
        <!-- <el-table-column label="办卡时间" align="center" prop="applyCardTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.applyCardTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column> -->
        <!-- <el-table-column label="有效期至" align="center" prop="endDate" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column> -->
        <!-- <el-table-column label="会员卡次数" align="center" prop="residueCount" /> -->
        <!-- <el-table-column label="到访备注" align="center" prop="visitRemark" /> -->
        <!-- <el-table-column label="跟进状态" align="center" prop="followStatus" /> -->
        <!-- <el-table-column label="会员状态" align="center" prop="memberStatus" /> -->
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['primary:member:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                v-hasPermi="['primary:member:remove']"></el-button>
            </el-tooltip>
            <el-tooltip content="查看详情" placement="top">
              <el-button link type="primary" icon="User" @click="handleuser(scope.row)"
                v-hasPermi="['primary:member:edit']"></el-button>
            </el-tooltip>
            <!--           <el-tooltip content="重新下发" placement="top">
              <el-button link type="primary" icon="Refresh" @click="handleUpdateResh(scope.row)"
                v-hasPermi="['primary:member:edit']"></el-button>
            </el-tooltip> -->
            <el-tooltip content="订单下发" placement="top">
              <el-button link type="primary" icon="Plus" @click="handleAddOrder(scope.row)"
                v-hasPermi="['primary:member:edit']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <el-dialog :title="dialogCamera.title" v-model="dialogCamera.visible" width="1200px" append-to-body>
      <div id="app">
        <Camera />
      </div>
    </el-dialog>

    <!-- 添加或修改会员信息对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="1200px" append-to-body>
      <el-form ref="memberFormRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="图片" prop="ossId">
          <imageUpload v-model="form.ossId" ref="childValue" :limit="1" :fileSize="1" :rule="1" />
        </el-form-item>

        <el-form-item label="会员姓名" prop="memberName">
          <el-input v-model="form.memberName" placeholder="请输入会员姓名" :disabled="dialog.isshow==3"
            @input="trimInput('memberName')" />
        </el-form-item>

        <el-form-item label="会员性别" prop="memberSex">
          <el-select v-model="form.memberSex" placeholder="请选择" :disabled="dialog.isshow==3">
            <el-option v-for="dict in sys_user_sex" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <!-- v-if="dialog.value==1" -->
        <el-form-item label="跟进人" prop="followUpPersonId">
          <el-select v-model="form.followUpPersonId" placeholder="请选择" filterable clearable
            :disabled="dialog.isshow==3">
            <el-option v-for="dict in coachList" :key="dict.id" :label="dict.coachName" :value="dict.id"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="会员手机号" prop="phoneNumber">
          <el-input v-model="form.phoneNumber" placeholder="请输入会员手机号" type="text" maxlength="11"
            :disabled="dialog.isshow==3" @input="trimInput('phoneNumber')" />
        </el-form-item>
        <el-form-item label="会员身份证" prop="idCard">
          <el-input v-model="form.idCard" placeholder="请输入会员身份证" :disabled="dialog.isshow==3"
            @input="trimInput('idCard')" />
        </el-form-item>
        <!--        <el-form-item label="会员类型" prop="memberType">
          <el-select v-model="form.memberType" placeholder="请选择" :disabled="dialog.isshow">
            <el-option v-for="dict in g_vip_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="到访类型" prop="visitType">
          <el-select v-model="form.visitType" placeholder="请选择" :disabled="dialog.isshow==3">
            <el-option v-for="dict in g_daofang_type" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="会员地址" prop="memberAddress">
          <el-input v-model="form.memberAddress" placeholder="请输入会员地址" :disabled="dialog.isshow==3"
            @input="trimInput('memberAddress')" />
        </el-form-item>
        <!--        <el-form-item label="会员生日" prop="birthday">
          <el-date-picker clearable v-model="form.birthday" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择会员生日" :disabled="dialog.isshow">
          </el-date-picker>
        </el-form-item> -->
        <!--              <el-form-item label="办卡所在店" prop="gymId" v-if='dialog.value == 3'>
          <el-input v-model="form.gymId" placeholder="请输入" :disabled='dialog.isshow' />
        </el-form-item> -->
        <!--        <el-form-item label="会员卡名称" prop="cardName" v-if='dialog.value == 3'>
          <el-input v-model="form.cardName" placeholder="请输入" :disabled='dialog.isshow' />
        </el-form-item> -->
        <!-- <div style="font-size: 18px;margin-bottom: 18px;">会员卡信息</div>
        <el-form-item label="选择会员卡" prop="cardId" v-if="dialog.isshow==1">
          <el-select v-model="form.cardId" placeholder="请选择" filterable clearable @change="handleSelectChange">
            <el-option v-for="dict in clubCardLista" :key="dict.id" :label="dict.cardName" :value="dict.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="课程教练" prop="coachId" v-if="dialog.isshow==1 &&dialogb.isshowkecheng">
          <el-select v-model="form.coachId" placeholder="请选择" filterable>
            <el-option v-for="dict in coachList" :key="dict.id" :label="dict.coachName" :value="dict.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开卡时间" prop="applyCardTime" v-if="dialog.isshow==1">
          <el-date-picker clearable v-model="form.applyCardTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择办卡时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="有效期至" prop="endDate" v-if="dialog.isshow==1">
          <el-date-picker clearable v-model="form.endDate" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择有效期至">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="会员卡次数" prop="residueCount" v-if="dialog.isshow==1 && dialogb.isshowcishu">
          <el-input v-model="form.residueCount" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="IC卡号" prop="icCard" v-if="dialog.isshow==1">
          <el-input v-model="form.icCard" placeholder="请输入IC卡号" />
        </el-form-item> -->
      </el-form>
      <!--      <el-card shadow="never" v-if="dialog.isshow!=1">
        <el-table v-loading="loading" :data="form.memberCardVos">
          <el-table-column label="办卡所在店" align="center" prop="gymId" />
          <el-table-column label="会员卡名称" align="center" prop="cardName" />
          <el-table-column label="IC卡号" align="center" prop="icCard" />
          <el-table-column label="跟进教练" align="center" prop="coachName" />
          <el-table-column label="剩余次数" align="center" prop="residueCount" />
          <el-table-column label="办卡时间" align="center" prop="createTime" />
          <el-table-column label="开卡时间" align="center" prop="applyCardTime" />
          <el-table-column label="有效期至" align="center" prop="endDate" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" v-if="dialog.isshow==2">
            <template #default="scope">
              <el-tooltip content="修改" placement="top" v-if="scope.row.openCard==0 || scope.row.openCard==null">
                <el-button link type="primary" icon="Edit" @click="handleUpdateCard(scope.row)"></el-button>
              </el-tooltip>
              <el-tooltip content="停卡" placement="top" v-if="scope.row.openCard==0 || scope.row.openCard==null">
                <el-button link type="primary" icon="CircleClose" @click="handleStopCard(scope.row)"></el-button>
              </el-tooltip>
              <el-tooltip content="开卡" placement="top" v-if="scope.row.openCard==2">
                <el-button link type="primary" icon="CirclePlus" @click="handleKaiCard(scope.row)"></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </el-card> -->
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm" v-if="dialog.value !=3">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 重新下发~~~~~~~~~~~~~~~~~~~~ -->
    <el-dialog :title="dialogResh.title" v-model="dialogResh.visible" width="1200px" append-to-body>
      <el-form ref="memberFormRef" :model="FormResh" label-width="100px">
        <!--        <el-form-item label="图片" prop="ossId">
          <imageUpload v-model="form.ossId" ref="childValue" :limit="1" :fileSize="1" :rule="1" />
        </el-form-item> -->
        <el-form-item label="设备选择" prop="deviceId">
          <el-select v-model="FormResh.deviceId" placeholder="请选择" filterable multiple>
            <el-option v-for="dict in deviceList" :key="dict.id" :label="dict.deviceName" :value="dict.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitFormResh">确 定</el-button>
          <el-button @click="cancelResh">取 消</el-button>
        </div>
      </template>
    </el-dialog>



    <!-- 新增订单对话框 -->
    <el-dialog :title="dialogOrder.title" v-model="dialogOrder.visible" width="560px" append-to-body>
      <el-form ref="orderFormRef" :model="Orderform" :rules="rules" label-width="110px">

        <el-form-item label="选择会员卡" prop="cardId">
          <el-select v-model="Orderform.cardId" placeholder="请选择" filterable clearable
            @change="handleSelectChangeOrder">
            <el-option v-for="dict in clubCardLista" :key="dict.id" :label="dict.cardName" :value="dict.id"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="订单数量" prop="orderNum">
          <el-input v-model="Orderform.orderNum" placeholder="请输入订单数量" type="number" :min="1" />
        </el-form-item>


        <el-form-item label="开卡日期" prop="registerCardTime">
          <el-date-picker clearable v-model="Orderform.registerCardTime" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择开卡日期">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="销售人" prop="coachId" v-if="dialogOrder.isshowCoach">
          <el-select v-model="Orderform.coachId" placeholder="请选择" filterable clearable>
            <el-option v-for="dict in coachListOrder" :key="dict.id" :label="dict.coachName"
              :value="dict.id"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="销售类型" prop="marketType">
          <el-select v-model="Orderform.marketType" placeholder="请选择">
            <el-option v-for="item in g_market_type" :key="item.value" :label="item.label"
              :value="item.value.toString()" />
          </el-select>
        </el-form-item>
        <el-form-item label="赠送时间(天)" prop="giveTime" v-if="dialogOrder.isshowkecheng">
          <el-input v-model="Orderform.giveTime" placeholder="请输入赠送时间" type="number" :min="0" />
        </el-form-item>

        <el-form-item label="支付方式" prop="payMethod">
          <el-select v-model="Orderform.payMethod" placeholder="请选择">
            <el-option v-for="dict in g_pay_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="IC卡号(选填)" prop="icCard">
          <el-input v-model="Orderform.icCard" placeholder="请输入IC卡号" type="text" @input="trimInput('icCard')" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitFormOrder">确 定</el-button>
          <el-button @click="cancelOrder">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Member" lang="ts">
  import { listMember, getMember, delMember, addMember, addMembertwo, updateMember, daochu, daoru, updateStop, updateRePush } from '@/api/primary/member';
  import { listOrder, getOrder, delOrder, addOrder, updateOrder, addOrderpay, refundOrder } from '@/api/primary/order';
  import { listGym } from '@/api/primary/gym';
  import { listDevice } from '@/api/primary/device';
  import { listClubCard, getClubCard } from '@/api/primary/clubCard';
  import { MemberVO, MemberQuery, MemberForm } from '@/api/primary/member/types';
  import { listRole } from "@/api/system/role";
  import { listCoach } from '@/api/primary/coach';
  import { nextTick } from 'vue';
  import { defineComponent } from 'vue';

  import Camera from '@/components/Camera';

  // export default defineComponent({
  //   name: 'App',
  //   components: {
  //     Camera
  //   }
  // })

  const { proxy } = getCurrentInstance() as ComponentInternalInstance;
  const { sys_user_sex, g_df_type, g_vip_type, g_daofang_type, sys_sync_status } = toRefs<any>(proxy?.useDict("sys_user_sex", 'g_df_type', 'g_vip_type', 'g_daofang_type', "sys_sync_status"));
  const { orderstats, g_pay_type, g_market_type } = toRefs<any>(proxy?.useDict("orderstats", "g_pay_type", "g_market_type"));
  const memberList = ref<MemberVO[]>([]);
  const buttonLoading = ref(false);
  const loading = ref(true);
  const showSearch = ref(true);
  const valueTime = ref('')
  const valueTime2 = ref('')
  const gymList = ref<any>();
  const coachListOrder = ref<any>([]);

  const dialogOrder = reactive<DialogOption>({
    visible: false,
    title: '',
    isdis: 0,
    isshowkecheng: undefined,
    isshowCoach: undefined
  });
  const payinfo = ref<any>({
    id: undefined,
    payMethod: 'CASH'
  });
  const Orderform = ref<any>({
    id: undefined,
    icCard: undefined,
    memberCardId: undefined,
    gymRefundRuleId: undefined,
    giveTime: undefined,
    gymId: undefined,
    memberType: undefined,
    coachId: undefined,
    memberId: undefined,
    cardId: undefined,
    orderNo: undefined,
    orderNum: 1,
    orderPrice: undefined,
    thirdPartyOrderNo: undefined,
    amount: undefined,
    payTime: undefined,
    indateTime: undefined,
    orderStatus: undefined,
    registerCardTime: undefined,
    gymUserId: undefined,
    marketType: undefined,
    memberName: undefined,
    payMethod: undefined
  });



  const shortcuts = [
    {
      text: '七天内失效',
      value: () => {
        const end = new Date()
        const start = new Date()
        end.setTime(start.getTime() + 3600 * 1000 * 24 * 7)
        return [start, end]
      },
    },
    {
      text: '十四天内失效',
      value: () => {
        const end = new Date()
        const start = new Date()
        end.setTime(start.getTime() + 3600 * 1000 * 24 * 14)
        return [start, end]
      },
    },
    {
      text: '三十天内失效',
      value: () => {
        const end = new Date()
        const start = new Date()
        end.setTime(start.getTime() + 3600 * 1000 * 24 * 30)
        return [start, end]
      },
    },
  ]
  const shortcutsa = [
    {
      text: '七天内新增',
      value: () => {
        const end = new Date()
        const start = new Date()
        start.setDate(start.getDate() - 7)
        return [start, end]
      },
    },
    {
      text: '十五天内新增',
      value: () => {
        const end = new Date()
        const start = new Date()
        start.setDate(start.getDate() - 15)
        return [start, end]
      },
    },
    {
      text: '三十天内新增',
      value: () => {
        const end = new Date()
        const start = new Date()
        start.setDate(start.getDate() - 30)
        return [start, end]
      },
    }
  ]
  const dataoo = reactive({
    options: [
      { value: 0, label: '有效会员' },
      { value: 1, label: '过期会员' }
    ]
  })
  const stateData = reactive({
    options: [
      { value: 0, label: '未同步' },
      { value: 1, label: '已同步' },
      { value: 2, label: '同步中' },
      { value: 3, label: '删除中' }
    ]
  })
  const ids = ref<Array<string | number>>([]);
  const idsname = ref<Array<string | number>>([]);
  const single = ref(true);
  const clubCardLista = ref<any>([]);
  const deviceList = ref<any>([]);
  const multiple = ref(true);
  const total = ref(0);
  const type = ref(0);
  const deviceArr = ref<any>([]);
  const coachList = ref<any>([]);
  const kechengcoachList = ref<any>([]);
  const roleCan = ref<any>();
  const roleList = ref<any>();
  const cardInfo = ref<any>();
  const imageUploadRef = ref(null);
  const queryFormRef = ref<ElFormInstance>();
  const memberFormRef = ref<ElFormInstance>();
  const clubCardFormRef = ref<ElFormInstance>();
  const orderFormRef = ref<ElFormInstance>();
  const dialog = reactive<DialogOption>({
    visible: false,
    title: '',
    value: '',
    isshow: -1
  });
  const dialogResh = reactive<DialogOption>({
    visible: false,
    title: ''
  });
  const dialogCamera = reactive<DialogOption>({
    visible: false,
    title: '相机拍照'
  });
  const dialogb = reactive<DialogOption>({
    visible: false,
    title: '',
    isshowkecheng: false,
    isshowcishu: false
  });
  const dialogc = reactive<DialogOption>({
    visible: false,
    title: '',
    isshowkecheng: false,
    isshowcishu: false
  });
  const dialogCard = reactive<DialogOption>({
    visible: false,
    title: ''
  });
  const cardForm = ref<any>({
    id: undefined,
    residueCount: undefined,//会员卡次数
    endDate: undefined,//会员卡有效期
    applyCardTime: undefined,//办卡日期
    coachId: undefined,//课程教练
    cardId: undefined,//会员卡id
    icCard: undefined//卡号
  });
  const FormResh = ref<any>({
    id: undefined,
    deviceId: undefined//
  });
  let childValue = ref();
  let fileinfo = ref();
  const gymIdValue = ref();
  const defaultSort = ref({ prop: 'createTime', order: 'ascending' });
  const initFormData : MemberForm = {
    //fileinfo: undefined,
    id: undefined,
    file: undefined,
    cardId: undefined,
    expireStartTime: undefined,
    expireEndTime: undefined,
    memberCardVos: undefined,
    followUpPersonId: undefined,
    coachId: undefined,
    memberName: undefined,
    memberType: 1,
    gymUserId: undefined,
    visitType: undefined,
    memberSex: undefined,//性别
    phoneNumber: undefined,
    idCard: undefined,
    memberAddress: undefined,
    ossId: undefined,
    birthday: undefined,
    applyCardTime: undefined,
    endDate: undefined,
    visitRemark: undefined,
    followStatus: undefined,
    memberStatus: undefined,
    residueCount: undefined,
  }
  const data = reactive<PageData<MemberForm, MemberQuery>>({
    form: { ...initFormData },
    queryParams: {
      icCard: undefined,
      fileName: '',
      isValid: undefined,
      expireStartTime: undefined,
      expireEndTime: undefined,
      startTime: undefined,
      stopTime: undefined,
      creationTime: undefined,
      createTime: '',
      originalName: '',
      fileSuffix: '',
      service: '',
      coachId: undefined,
      // orderByColumn: defaultSort.value.prop,
      // isAsc: defaultSort.value.order,
      pageNum: 1,
      pageSize: 10,
      cardId: undefined,
      residueCount: undefined,
      memberName: undefined,
      isSync: undefined,
      daysUntilExpire: undefined,
      memberType: 1,
      gymUserId: undefined,
      visitType: undefined,
      memberSex: undefined,
      phoneNumber: undefined,
      idCard: undefined,
      memberAddress: undefined,
      // ossId: undefined,
      birthday: undefined,
      applyCardTime: undefined,
      endDate: undefined,
      visitRemark: undefined,
      followUpPersonId: undefined,
      followStatus: undefined,
      memberStatus: undefined,
      params: {
      }
    },
    rules: {
      orderNum: [
        { required: true, message: "订单数量不能为空", trigger: "change" }
      ],
      memberName: [
        { required: true, message: "会员姓名不能为空", trigger: "blur" }
      ],
      // ossId: [
      //   { required: true, message: "图片不能为空", trigger: "blur" }
      // ],
      file: [
        { required: true, message: "文件不能为空", trigger: "blur" }
      ],
      cardId: [
        { required: true, message: "会员卡不能为空", trigger: "blur" }
      ],
      memberType: [
        { required: true, message: "会员类型不能为空", trigger: "change" }
      ],
      gymUserId: [
        { required: true, message: "跟进教练不能为空", trigger: "blur" }
      ],
      visitType: [
        { required: true, message: "到访类型不能为空", trigger: "change" }
      ],
      memberSex: [
        { required: true, message: "会员性别不能为空", trigger: "change" }
      ],
      phoneNumber: [
        { required: true, message: "会员手机号不能为空", trigger: "blur" }
      ],
      birthday: [
        { required: false, message: "会员生日不能为空", trigger: "blur" }
      ],
      applyCardTime: [
        { required: true, message: "办卡时间不能为空", trigger: "blur" }
      ],
      endDate: [
        { required: true, message: "有效期至不能为空", trigger: "blur" }
      ],

      coachId: [
        { required: true, message: "教练不能为空", trigger: "blur" }
      ],
      residueCount: [
        { required: true, message: "会员卡次数不能为空", trigger: "blur" }
      ],

      icCard: [
        { required: false, message: "IC卡号", trigger: "change" }
      ],
      payTime: [
        { required: true, message: "支付时间不能为空", trigger: "change" }
      ],
      indateTime: [
        { required: true, message: "有效期至不能为空", trigger: "blur" }
      ],

      registerCardTime: [
        { required: true, message: "办卡日期不能为空", trigger: "blur" }
      ],
      marketType: [
        { required: true, message: "销售类型不能为空", trigger: "change" }
      ],
      payMethod: [
        { required: true, message: "支付方式", trigger: "change" }
      ]
    },

  });

  const { queryParams, form, rules } = toRefs(data);
  /** 当日按钮操作 */
  const handleData = () => {
    queryParams.value.startTime = undefined
    queryParams.value.stopTime = undefined
    queryParams.value.pageNum = 1;
    const date = new Date();
    const createISOString = date.toISOString();
    const create = createISOString.split('T')[0];
    queryParams.value.creationTime = create
    getList();
  }
  const trimInput = (field) => {
    nextTick(() => {
      if (form.value[field]) {
        form.value[field] = form.value[field].trim();
      }
    });
  };
  /** 三日与一周按钮操作 */
  const handleDatatime = (e) => {
    console.log(e, 'eeeeeeeeee')
    queryParams.value.creationTime = undefined
    queryParams.value.pageNum = 1;
    // 获取当前日期
    const currentDate = new Date();
    // 设置开始日期为当前日期前2天
    const startOfPeriod = new Date(currentDate);
    startOfPeriod.setDate(currentDate.getDate() - e); // 当天算一天，再往前两天
    // 设置结束日期为当前日期
    const endOfPeriod = new Date(currentDate);

    // 将日期格式转换为 ISO 8601 格式的字符串
    const startISOString = startOfPeriod.toISOString();
    const endISOString = endOfPeriod.toISOString();
    // 提取日期部分，忽略时间部分
    const start = startISOString.split('T')[0];
    const end = endISOString.split('T')[0];
    // 将日期格式从 yyyy-mm-dd 转换为 yyyy-mm-dd 00:00:00
    let formattedStartDate = start + ' 00:00:00';
    let formattedEndDate = end + ' 23:59:59';
    queryParams.value.startTime = formattedStartDate
    queryParams.value.stopTime = formattedEndDate
    console.log("从当天起往前数3天内的开始日期是：" + queryParams.value.startTime);
    console.log("从当天起往前数3天内的结束日期是：" + queryParams.value.stopTime);
    getList();
  }
  const updateExpireEndTime = () => {
    if (valueTime.value) {
      const StartTime = new Date(valueTime.value[0]).toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit'
      }).replace(/\//g, '-');
      queryParams.value.expireStartTime = StartTime + ' 00:00:00';

      const EndTime = new Date(valueTime.value[1]).toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit'
      }).replace(/\//g, '-');
      queryParams.value.expireEndTime = EndTime + ' 23:59:59';

    } else {
      queryParams.value.expireStartTime = undefined
      queryParams.value.expireEndTime = undefined
    }

  }
  const updateExpireEndTime2 = () => {
    if (valueTime2.value) {
      queryParams.value.startTime = valueTime2.value[0] + ' 00:00:00';
      queryParams.value.stopTime = valueTime2.value[1] + ' 23:59:59';
    } else {
      queryParams.value.startTime = undefined
      queryParams.value.stopTime = undefined
    }

  }
  /** 查询会员信息列表 */
  const getList = async () => {
    // updateExpireEndTime()
    // updateExpireEndTime2()
    loading.value = true;
    const res = await listMember(queryParams.value);
    memberList.value = res.rows;
    total.value = res.total;
    if (total.value > 0) {
      gymIdValue.value = res.rows[0].gymId
    }

    loading.value = false;
  }
  /** 查询会员卡信息列表 */
  const getListcard = async () => {

    const res = await listClubCard(queryParams.value);
    clubCardLista.value = res.rows;
    console.log(clubCardLista.value, '会员卡列表')

  }

  /** 新增按钮操作 */
  const handleAddOrder = async (row ?: MemberVO) => {
    resetQueryOrder();
    const _id = row?.id || ids.value[0]
    const res = await getMember(_id);
    Orderform.value.memberId = res.data.id
    console.log(Orderform.value.memberId, Orderform.value.memberId)
    dialogOrder.isdis = false
    dialogOrder.visible = true;
    dialogOrder.title = "添加订单信息";
  }

  const handleSelectChangeOrder = (selectedId) => {
    coachListOrder.value = undefined
    let selectedDict = clubCardLista.value.find(dict => dict.id === selectedId);
    if (selectedDict) {
      console.log('Selected memberCourseType:0会员 1课程', selectedDict.memberCourseType);
      console.log('Selected cardType:卡种;0期限卡 1次卡', selectedDict.cardType);
      let cardId = selectedDict.id
      console.log(cardId, '选中的会员卡信息');
      if (selectedDict.memberCourseType == 1) {
        getcoach(cardId)
      }

      if (selectedDict.memberCourseType == 0) {
        Orderform.value.coachId = ''
        dialogOrder.isshowCoach = false
      } else {
        Orderform.value.coachId = ''
        dialogOrder.isshowCoach = true
      }
      //卡种;0期限卡 1次卡',
      if (selectedDict.cardType == 1) {
        Orderform.value.giveTime = ''
        dialogOrder.isshowkecheng = false
      } else {
        Orderform.value.giveTime = ''
        dialogOrder.isshowkecheng = true
      }

    }
  }

  /** 提交按钮 */
  const submitFormOrder = () => {
    orderFormRef.value?.validate(async (valid : boolean) => {
      if (valid) {
        buttonLoading.value = true;
        if (Orderform.value.id) {
          await updateOrder(Orderform.value).finally(() => buttonLoading.value = false);
          proxy?.$modal.msgSuccess("修改成功");
        } else {
          if (Orderform.value.payMethod == '0') {
            Orderform.value.payMethod = 'SCANPAY'
            payinfo.value.payMethod = 'SCANPAY'
          }
          if (Orderform.value.payMethod == '1') {
            payinfo.value.payMethod = 'CASH'
            Orderform.value.payMethod = 'CASH'
          }
          Orderform.value.gymId = gymList.value[0].id
          console.log(Orderform.value.gymId, '~~~~~~~@@@@@@@@@@@@~~~~~')
          const res = await addOrder(Orderform.value).finally(() => buttonLoading.value = false);
          payinfo.value.id = res.data.id
          console.log(payinfo.value.id, 'ssssssssssssssssss')
          await addOrderpay(payinfo.value).finally(() => buttonLoading.value = false);
          proxy?.$modal.msgSuccess("下单成功");
          queryParams.value.cardId = ''
          queryParams.value.memberId = ''
        }

        dialogOrder.visible = false;
        dialogOrder.isshowkecheng = undefined
        dialogOrder.isshowCoach = undefined
        await getList();
      }
    });
  }





  /** 查询设备列表 */
  const getListDevice = async () => {
    loading.value = true;
    const res = await listDevice(queryParams.value);
    deviceList.value = res.rows;
    deviceArr.value = res.rows.map(item => item.id);
    console.log(deviceArr.value, 'deviceArr.valuedeviceArr.value')
  }


  const handleSelectChange = (selectedId) => {
    console.log(selectedId, 'selectedIdselectedIdselectedId')
    const selectedDict = clubCardLista.value.find(dict => dict.id === selectedId);
    if (selectedDict) {
      console.log('Selected memberCourseType:0会员 1课程', selectedDict.memberCourseType);
      console.log('Selected cardType:0期限卡 1次卡', selectedDict.cardType);
      // 0会员 1课程
      if (selectedDict.memberCourseType == 0) {
        form.value.coachId = ''
        form.value.residueCount = ''
        dialogb.isshowkecheng = false
      } else {
        dialogb.isshowkecheng = true
      }
      //卡种;0期限卡 1次卡',
      if (selectedDict.cardType == 0) {
        form.value.residueCount = ''
        dialogb.isshowcishu = false
      } else {
        dialogb.isshowcishu = true
      }
    }
  }

  // const handleSelectChangeCard = (selectedId) => {
  //   const selectedDict = clubCardLista.value.find(dict => dict.id === selectedId);
  //   if (selectedDict) {
  //     console.log('Selected memberCourseType:', selectedDict.memberCourseType);
  //     console.log('Selected cardType:', selectedDict.cardType);
  //     // 0会员 1课程
  //     if (selectedDict.memberCourseType == 0) {
  //       cardForm.value.coachId = ''
  //       cardForm.value.residueCount = ''
  //       dialogc.isshowkecheng = false
  //     } else {
  //       dialogc.isshowkecheng = true
  //     }
  //     //卡种;0期限卡 1次卡',
  //     if (selectedDict.cardType == 0) {
  //       cardForm.value.residueCount = ''
  //       dialogc.isshowcishu = false
  //     } else {
  //       dialogc.isshowcishu = true
  //     }
  //   }
  // }

  const handleFile = () => {
    reset();
    dialogb.visible = true;
    dialogb.title = "上传文件";
  }
  /** 提交按钮 */
  const submitFormb = () => {
    console.log(form.value.file, '~~~~~~~~~~~~~~~~~~')
    dialogb.visible = false;
    location.reload(true)
  }
  /** 取消按钮 */
  const cancel = () => {
    reset();
    dialogb.isshowkecheng = false
    dialogb.isshowcishu = false
    dialog.visible = false
  }
  /** 取消按钮 */
  const cancelResh = () => {
    reset();
    dialogResh.visible = false
  }
  const cancelb = () => {
    location.reload(true)
    dialogb.visible = false;
  }
  const getListb = async () => {
    console.log('111111')
    const res = await listCoach(queryParams.value);
    coachList.value = res.rows;
    console.log(coachList.value, '教练信息表')
  }
  const getListcoach = async () => {
    console.log('111111')
    const res = await listCoach(queryParams.value);
    kechengcoachList.value = res.rows;
    console.log(kechengcoachList.value, '教练信息表')
  }
  /** 课程卡教练列表 */
  const getcoach = async (e ?: any) => {
    const _id = e
    const res = await getClubCard(_id);
    coachListOrder.value = res.data.coaches;
    console.log(coachListOrder.value, 'coachListOrder教练信息表')
  }
  /** 表单重置 */
  const reset = () => {
    form.value = { ...initFormData };
    memberFormRef.value?.resetFields();
  }

  /** 搜索按钮操作 */
  const handleQuery = () => {
    queryParams.value.creationTime = undefined
    queryParams.value.pageNum = 1;
    getList();
  }
  /** 取消按钮 */
  const cancelOrder = () => {
    reset();
    dialogOrder.visible = false;
    dialogOrder.isshowkecheng = undefined
    dialogOrder.isshowCoach = undefined
  }
  /** 重置按钮操作 */
  const resetQuery = () => {
    valueTime2.value = undefined
    queryParams.value.startTime = undefined
    queryParams.value.stopTime = undefined
    queryParams.value.creationTime = undefined
    valueTime.value = undefined
    queryParams.value.expireStartTime = undefined
    queryParams.value.expireEndTime = undefined
    queryParams.value.isValid = undefined
    queryParams.value.isSync = undefined
    queryParams.value.daysUntilExpire = undefined
    queryFormRef.value?.resetFields();
    handleQuery();
  }
  const resetQueryOrder = () => {
    Orderform.value.id = undefined
    Orderform.value.icCard = undefined
    Orderform.value.memberCardId = undefined
    Orderform.value.gymRefundRuleId = undefined
    Orderform.value.giveTime = undefined
    Orderform.value.gymId = undefined
    Orderform.value.memberType = undefined
    Orderform.value.coachId = undefined
    Orderform.value.memberId = undefined
    Orderform.value.cardId = undefined
    Orderform.value.orderNo = undefined
    Orderform.value.orderNum = 1
    Orderform.value.orderPric = undefined
    Orderform.value.thirdPartyOrderNo = undefined
    Orderform.value.amount = undefined
    Orderform.value.payTime = undefined
    Orderform.value.indateTime = undefined
    Orderform.value.orderStatus = undefined
    Orderform.value.registerCardTime = undefined
    Orderform.value.gymUserId = undefined
    Orderform.value.marketType = undefined
    Orderform.value.memberName = undefined
    Orderform.value.payMethod = undefined
  }

  const ClickCamera = () => {
    dialogCamera.visible = true
  }
  /** 多选框选中数据 */
  const handleSelectionChange = (selection : MemberVO[]) => {
    ids.value = selection.map(item => item.id);
    idsname.value = selection.map(item => item.memberName);
    single.value = selection.length != 1;
    multiple.value = !selection.length;


  }

  /** 新增按钮操作 */
  const handleAdd = () => {
    reset();
    dialog.visible = true;
    dialog.title = "添加会员信息";
    dialog.value = '1'
    dialog.isshow = 1;
  }

  /** 修改按钮操作 */
  const handleUpdate = async (row ?: MemberVO) => {
    reset();
    const _id = row?.id || ids.value[0]
    const res = await getMember(_id);
    Object.assign(form.value, res.data);
    dialog.visible = true;
    dialog.value = '2';
    dialog.isshow = 2;
    dialog.title = "修改会员信息";
  }

  /** 修改按钮操作 */
  const handleUpdateResh = async (row ?: MemberVO) => {
    reset();
    const _id = row?.id || ids.value[0]
    const res = await getMember(_id);
    Object.assign(form.value, res.data);
    dialogResh.visible = true;
    dialogResh.title = "重新下发";
  }
  /** 查看按钮操作 */
  const handleuser = async (row ?: MemberVO) => {
    reset();
    const _id = row?.id || ids.value[0]
    const res = await getMember(_id);
    Object.assign(form.value, res.data);
    dialog.visible = true;
    dialog.value = '3';
    dialog.isshow = 3;
    dialog.title = "会员详情";
  }
  /** 停卡按钮操作 */
  const handleStopCard = async (row ?: any) => {
    console.log(row, '@@@@@@@@@')
    let cardInfo = reactive<any>({
      memberCardId: undefined,
      openCard: 2
    })
    let name = row.cardName
    cardInfo.memberCardId = row.id
    await proxy?.$modal.confirm('是否确认将"' + name + '"停卡？').finally(() => loading.value = false);
    await updateStop(cardInfo);
    proxy?.$modal.msgSuccess("停卡成功");
    dialog.visible = false;
    dialogb.isshowkecheng = false
    dialogb.isshowcishu = false
    await getList();
  }
  /** 开卡按钮操作 */
  const handleKaiCard = async (row ?: any) => {
    console.log(row, '￥￥￥￥￥￥￥￥￥￥')
    let cardInfo = reactive<any>({
      memberCardId: undefined,
      openCard: 0
    })
    let name = row.cardName
    cardInfo.memberCardId = row.id
    cardInfo.deviceId = deviceArr.value
    await proxy?.$modal.confirm('是否确认将"' + name + '"开卡？').finally(() => loading.value = false);
    await updateStop(cardInfo);
    proxy?.$modal.msgSuccess("开卡成功");
    dialog.visible = false;
    dialogb.isshowkecheng = false
    dialogb.isshowcishu = false
    await getList();
  }
  /** 修改会员卡按钮操作 */
  const handleUpdateCard = async (row ?: any) => {
    // proxy?.$modal.msgSuccess("此功能正在测试中，请稍后");
    // return
    // reset();
    console.log(row, '@@@@@@@@@@')
    // const _id = row.id
    // const res = await getClubCard(_id);
    //Object.assign(cardForm.value, row);
    cardForm.value = row
    console.log('要修改的会员卡属性', cardForm.value)
    dialogCard.visible = true;
    dialogCard.title = "会员卡修改";
  }
  /** 查询健身房信息列表 */
  const getListgym = async () => {
    const res = await listGym(queryParams.value);
    gymList.value = res.rows;

  }
  /** 提交按钮 */
  const submitForm = () => {
    form.value.gymId = ''
    form.value.userId = ''
    form.value.memberType = 1
    memberFormRef.value?.validate(async (valid : boolean) => {
      if (valid) {
        buttonLoading.value = true;
        if (form.value.id) {
          await updateMember(form.value).finally(() => buttonLoading.value = false);
          proxy?.$modal.msgSuccess("修改成功");
        } else {
          console.log(form.value.followUpPersonId, '111111111111111111111')
          await addMembertwo(form.value).finally(() => buttonLoading.value = false);
          proxy?.$modal.msgSuccess("添加成功");
        }

        dialog.visible = false;
        dialogb.isshowkecheng = false
        dialogb.isshowcishu = false
        await getList();
      }
    });
  }
  /** 提交会员卡修改按钮 */
  const submitFormCard = async () => {
    console.log(cardForm.value, '更改过的会员卡信息')
    cardForm.value.gymId = undefined
    cardForm.value.id = cardForm.value.memberId
    buttonLoading.value = true;
    await updateMember(cardForm.value).finally(() => buttonLoading.value = false);
    proxy?.$modal.msgSuccess("修改成功");
    dialog.visible = false;
    dialogCard.visible = false;
    await getList();
  }
  /** 重新下发 */
  const submitFormResh = async () => {
    if (FormResh.value.deviceId.length == 0) {
      proxy?.$modal.msgError("请先选择设备!");
      return
    }
    FormResh.value.id = form.value.id
    FormResh.value.gymId = gymIdValue.value
    buttonLoading.value = true;
    await updateRePush(FormResh.value).finally(() => buttonLoading.value = false);
    proxy?.$modal.msgSuccess("提交成功");
    dialogResh.visible = false;
    await getList();
  }
  /** 导出按钮操作 */
  const handledaochu = async (row ?: any) => {
    await daochu();
    proxy?.$modal.msgSuccess("导出成功");
  }
  /** 导入按钮操作 */
  const handledaoru = async (row ?: any) => {
    await daoru();
    proxy?.$modal.msgSuccess("导入成功");
  }
  /** 删除按钮操作 */
  const handleDelete = async (row ?: MemberVO) => {
    console.log(row, '哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈')
    const _ids = row?.id || ids.value;
    const name = row?.memberName || idsname.value;

    await proxy?.$modal.confirm('是否确认删除会员为"' + name + '"的数据项？').finally(() => loading.value = false);
    await delMember(_ids);
    proxy?.$modal.msgSuccess("已提交,等待删除中");
    await getList();
  }

  /** 导出按钮操作 */
  const handleExport = () => {
    //proxy?.download('primary/member/aiUser/export', {
    proxy?.download('primary/member/export', {
      ...queryParams.value
    }, `member_${new Date().getTime()}.xlsx`)
  }
  const childRef = ref(null);
  onMounted(() => {
    queryParams.value.pageNum = undefined
    queryParams.value.pageSize = undefined
    getListb()
    getListcard()
    getListDevice()
    queryParams.value.pageNum = 1
    queryParams.value.pageSize = 10
    getList();
    getListgym()


  });
</script>
